package com.polito.mad.bikeponyapp.persistence;

import java.util.List;

import android.database.Cursor;
import android.database.SQLException;

public abstract class DAOProxy<T,K extends DAO<T>> implements DAO<T> {

	private K _dao;
	
	public DAOProxy( K dao) throws Exception
	{
		if(dao==null)
			throw new Exception("cannot prepare the DAO");
		_dao = dao;
	}
	
	@Override
	public List<T> getAll() {
		return _dao.getAll();
	}

	@Override
	public T getCursor(Cursor c) {
		return _dao.getCursor(c);
	}

	@Override
	public T get(long id) {
		return _dao.get(id);
	}

	@Override
	public T add(T entity) throws SQLException {
		T newEntity = _dao.add(entity);
		flushCachedObjects();
		notifyModelChanged();
		return newEntity;
	}
	public int deleteAll(List<T> entities)throws SQLException
	{
		int counteRemoved = _dao.deleteAll(entities);
		flushCachedObjects();
		notifyModelChanged();
		return counteRemoved;
	}

	@Override
	public void delete(T entity) throws SQLException {
		_dao.delete(entity);
		flushCachedObjects();
		notifyModelChanged();
	}

	@Override
	public T update(T item) throws SQLException {
		T updatedItem = _dao.update(item);
		flushCachedObjects();
		notifyModelChanged();
		return updatedItem;
		
	}

	@Override
	public List<T> updateAll(List<T> items) throws SQLException {
		List<T> updatedItems = _dao.updateAll(items);
		flushCachedObjects();
		notifyModelChanged();
		return updatedItems;
	}
	@Override
	public List<T> findByQuery(String query) {
		return _dao.findByQuery(query);
	}
	@Override
	public List<T> addAll(List<T> entities) throws SQLException {
		List<T>newItems = _dao.addAll(entities);
		flushCachedObjects();
		notifyModelChanged();
		return newItems;
	}
	@Override
	public int count() {
		return _dao.count();
	}
	@Override
	public void close() {
		_dao.close();
		
	}
	@Override
	public Cursor getAllAsCursor() {
		return _dao.getAllAsCursor();
	}
	
	@Override
	public String getColumnNameByIndex(int colIndex) {
		return _dao.getColumnNameByIndex(colIndex);
	}
	protected abstract void  notifyModelChanged();
	protected abstract void  notifyResourcesClosed();
	protected abstract void flushCachedObjects();
}
